<template>
  <div class="channel-management">
    <div class="header">
      <h2>채널 관리</h2>
      <div class="actions">
        <el-input v-model="search" placeholder="채널명 검색" clearable style="width: 220px" @keyup.enter.native="fetchChannels" />
        <el-button type="primary" @click="openCreate">채널 생성</el-button>
      </div>
    </div>

    <el-table :data="channels" v-loading="loading" style="width:100%">
      <el-table-column prop="id" label="ID" width="90" />
      <el-table-column label="프로필 이미지" width="120">
        <template #default="{ row }">
          <img v-if="row.avatarUrl" :src="`${API_BASE_URL}${row.avatarUrl}`" alt="avatar" style="width:60px;height:60px;border-radius:50%;object-fit:cover" />
          <span v-else class="no-cover">없음</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="이름" min-width="200" />
      <el-table-column prop="description" label="설명" min-width="260" />
      <el-table-column prop="isActive" label="활성화" width="100">
        <template #default="{ row }">
          <el-tag :type="row.isActive ? 'success' : 'info'">{{ row.isActive ? '예' : '아니오' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="생성 시간" width="180">
        <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
      </el-table-column>
      <el-table-column label="작업" width="220" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">편집</el-button>
          <el-button size="small" type="danger" :loading="row.deleting" @click="deleteChannel(row)">삭제</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        @current-change="fetchChannels"
      />
    </div>

    <el-dialog v-model="showDialog" :title="editing ? '채널 편집' : '채널 생성'" width="560px">
      <el-form :model="form" label-width="90px">
        <el-form-item label="이름" required>
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="설명">
          <el-input v-model="form.description" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="프로필 이미지">
          <el-upload
            class="uploader"
            :action="`${API_BASE_URL}/api/admin/uploads/cover`"
            name="cover-upload"
            :with-credentials="true"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
          >
            <img v-if="form.avatarUrl" :src="`${API_BASE_URL}${form.avatarUrl}`" class="cover" />
            <el-button v-else type="primary">이미지 선택</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="활성화">
          <el-switch v-model="form.isActive" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">취소</el-button>
        <el-button type="primary" :loading="saving" :disabled="!form.name" @click="save">{{ editing ? '저장' : '생성' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

const loading = ref(false)
const channels = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const search = ref('')

const showDialog = ref(false)
const editing = ref(false)
const saving = ref(false)
let currentId: string | null = null

const form = ref({ name: '', description: '', avatarUrl: '', isActive: true })

const fetchChannels = async () => {
  loading.value = true
  try {
    const resp = await request.get('/api/admin/channels', { params: { page: currentPage.value, limit: pageSize.value, search: search.value } })
    channels.value = resp.data.channels
    total.value = resp.data.total
  } catch (e) {
    ElMessage.error('채널 가져오기 실패')
  } finally {
    loading.value = false
  }
}

const openCreate = () => { editing.value = false; currentId = null; form.value = { name: '', description: '', avatarUrl: '', isActive: true }; showDialog.value = true }
const openEdit = (row: any) => { editing.value = true; currentId = String(row.id); form.value = { name: row.name, description: row.description || '', avatarUrl: row.avatarUrl || '', isActive: !!row.isActive }; showDialog.value = true }

const handleCoverSuccess = (res: any) => {
  // 서버에서 { coverUrl } 최상위 필드 반환
  if (res?.coverUrl) form.value.avatarUrl = res.coverUrl
}

const save = async () => {
  if (!form.value.name) return
  saving.value = true
  try {
    if (editing.value && currentId) {
      await request.put(`/api/admin/channels/${currentId}`, form.value)
      ElMessage.success('저장 성공')
    } else {
      await request.post('/api/admin/channels', form.value)
      ElMessage.success('생성 성공')
    }
    showDialog.value = false
    fetchChannels()
  } catch (e) {
    ElMessage.error(editing.value ? '저장 실패' : '생성 실패')
  } finally {
    saving.value = false
  }
}

const deleteChannel = async (row: any) => {
  try {
    await ElMessageBox.confirm('이 채널을 삭제하시겠습니까?\n주의: 채널에 연결된 비디오나 라이브 방이 있으면 삭제할 수 없습니다.', '삭제 확인', { type: 'warning' })
    row.deleting = true
    await request.delete(`/api/admin/channels/${row.id}`)
    ElMessage.success('삭제 성공')
    fetchChannels()
  } catch (e) {
    if (e !== 'cancel') ElMessage.error('삭제 실패')
  } finally {
    row.deleting = false
  }
}

const formatDate = (s: string) => new Date(s).toLocaleString('zh-CN')

onMounted(() => { fetchChannels() })
</script>

<style scoped>
.channel-management { padding: 20px; }
.header { display:flex; align-items:center; justify-content:space-between; margin-bottom:16px; }
.actions { display:flex; gap:10px; }
.no-cover { color:#999; font-size:12px; }
.pager { display:flex; justify-content:center; padding: 16px 0; }
.cover { width: 80px; height: 80px; border-radius: 6px; object-fit: cover; }
</style>

